package admin_service

import (
	"shop/dao"
	"shop/entity"
	"shop/service"
	"shop/utils/result"
	"time"
)

func GetShopConfig(shopId int) *result.Result {
	shopInfo := service.GetShopInfo(shopId)
	if shopInfo == nil || shopInfo.Id == 0 {
		return result.Fail("店铺不存在")
	}
	return result.Ok(shopInfo)
}

func UpdateShopConfig(shopId int, shop *entity.ShopFilter) *result.Result {
	rows := dao.GetTx().Model(shop).Where("id", shopId).Updates(shop).Commit().RowsAffected
	return result.Ok(rows)
}

func GetShopList(user *entity.SysUser) *result.Result {
	list := make([]*entity.Shop, 0, 0)
	dao.GetDB().Table(entity.TableNameShop).Find(&list)
	// 脱敏
	if user.PermissionSet["shop:merchantInfo"] == nil && user.PermissionSet["*"] == nil {
		mask := "无权限查看"
		for _, shop := range list {
			shop.WxPayMchId = mask
			shop.WxPayApiKey = mask
			shop.WxGzhAppId = mask
			shop.WxGzhAppSecret = mask
			shop.WxMpAppId = mask
			shop.WxMpAppSecret = mask
			shop.CertPEMPublicKey = mask
			shop.CertPEMPrivateKey = mask
			shop.MerchantName = mask
		}
	}
	return result.Ok(list)
}

func AddShop(shop *entity.Shop) *result.Result {
	shop.CreateTime = time.Now().UnixNano() / 1000_000
	rows := dao.GetTx().Model(shop).Create(shop).Commit().RowsAffected
	return result.Ok(rows)
}

func UpdateShop(shopId int, shop *entity.ShopFilter) *result.Result {
	db := dao.GetTx().Model(shop).Where("id", shopId).Updates(shop).Commit()
	if db.Error != nil {
		return result.Fail(db.Error.Error())
	}
	return result.Ok(db.RowsAffected)
}
